package com.jsb.laundry.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import com.jsb.laundry.common.exception.*;
import com.jsb.laundry.dao.JsbPostUserFollowersMapper;
import com.jsb.laundry.dao.JsbPostsMapper;
import com.jsb.laundry.model.dto.posts.*;
import com.jsb.laundry.model.entity.JsbPostLikes;
import com.jsb.laundry.model.entity.JsbPostUserFollowers;
import com.jsb.laundry.model.entity.JsbPosts;
import com.jsb.laundry.model.vo.PostsUserStatVO;
import com.jsb.laundry.model.vo.PostsVO;
import com.jsb.laundry.service.JsbPostUserFollowersService;
import com.jsb.laundry.service.JsbPostsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 帖子接口
 */
@RestController
@RequestMapping("/posts")
@Api(value = "帖子相关接口", tags = "帖子")
@Slf4j
public class PostController {
    private static final Logger LOGGER = LoggerFactory.getLogger(PostController.class);
    @Resource
    private JsbPostsService postService;

    @Resource
    private JsbPostsMapper postsMapper;

    @Resource
    private JsbPostUserFollowersService postUserFollowService;
    @Resource
    private JsbPostUserFollowersMapper postUserFollowersMapper;

    private final static Gson GSON = new Gson();

    // region 增删改查

    /**
     * 创建
     *
     * @param postAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    @ApiOperation("创建帖子")
    public BaseResponse<Long> addPost(@RequestBody PostAddRequest postAddRequest, HttpServletRequest request) {
        if (postAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        JsbPosts post = new JsbPosts();
        BeanUtils.copyProperties(postAddRequest, post);
//        List<String> tags = postAddRequest.getTags();
//        if (tags != null) {
//            post.setTags(GSON.toJson(tags));
//        }
        postService.validPost(post, true);
        boolean result = postService.save(post);
        LOGGER.info("PostController::addPost, result{}", result);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        long newPostId = post.getId();
        return ResultUtils.success(newPostId);
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    @ApiOperation("删除帖子")
    public BaseResponse<Boolean> deletePost(@RequestBody PostDelRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getPostId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 判断帖子是否存在
        JsbPosts oldPost = postService.getById(deleteRequest.getPostId());
        ThrowUtils.throwIf(oldPost == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人可删除
        if (!oldPost.getUserId().equals(deleteRequest.getUserId())) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = postService.removeById(deleteRequest.getPostId());
        return ResultUtils.success(b);
    }

//    /**
//     * 更新
//     *
//     * @param postUpdateRequest
//     * @return
//     */
//    @PostMapping("/update")
//    @ApiOperation("更新帖子")
//    public BaseResponse<Boolean> updatePost(@RequestBody PostUpdateRequest postUpdateRequest) {
//        if (postUpdateRequest == null || postUpdateRequest.getId() <= 0) {
//            throw new BusinessException(ErrorCode.PARAMS_ERROR);
//        }
//        JsbPosts post = new JsbPosts();
//        BeanUtils.copyProperties(postUpdateRequest, post);
//        List<String> tags = postUpdateRequest.getTags();
//        if (tags != null) {
//            post.setTags(GSON.toJson(tags));
//        }
//        // 参数校验
//        postService.validPost(post, false);
//        long id = postUpdateRequest.getId();
//        // 判断是否存在
//        JsbPosts oldPost = postService.getById(id);
//        ThrowUtils.throwIf(oldPost == null, ErrorCode.NOT_FOUND_ERROR);
//        boolean result = postService.updateById(post);
//        return ResultUtils.success(result);
//    }

    /**
     * 获取帖子用户统计信息
     *
     * @param postUserStatRequest
     * @return
     */
    @PostMapping("/get/user_stat")
    @ApiOperation("获取帖子用户统计信息")
    public BaseResponse<PostsUserStatVO> getPostUserStat(@RequestBody PostUserStatRequest postUserStatRequest, HttpServletRequest request) {
        if (postUserStatRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        if (StringUtils.isAnyBlank(postUserStatRequest.getUserId())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户id为空");
        }
        //关注数量
        QueryWrapper<JsbPostUserFollowers> postUserFollowQueryWrapper = new QueryWrapper<>();
        postUserFollowQueryWrapper.eq("user_id", postUserStatRequest.getUserId());
        int followerNum = postUserFollowersMapper.selectCount(postUserFollowQueryWrapper);

        //粉丝数量
        QueryWrapper<JsbPostUserFollowers> postUserFansQueryWrapper = new QueryWrapper<>();
        postUserFansQueryWrapper.eq("follower_id", postUserStatRequest.getUserId());
        int fansNum = postUserFollowersMapper.selectCount(postUserFansQueryWrapper);

        //发帖数量
        QueryWrapper<JsbPosts> postsQueryWrapper = new QueryWrapper<>();
        postsQueryWrapper.eq("user_id", postUserStatRequest.getUserId());
        int postsNum = postsMapper.selectCount(postsQueryWrapper);

        //获赞数量
        int likesReceivedNum = postService.getLikesReceivedNum(postUserStatRequest.getUserId());

        PostsUserStatVO userStatVO = new PostsUserStatVO();
        userStatVO.setFollowerNum(followerNum);
        userStatVO.setFansNum(fansNum);
        userStatVO.setPostsNum(postsNum);
        userStatVO.setLikesReceivedNum(likesReceivedNum);

        return ResultUtils.success(userStatVO);
    }

    /**
     * 根据 id 获取
     *
     * @param postQueryRequest
     * @return
     */
    @PostMapping("/get/vo")
    @ApiOperation("根据帖子id获取详情")
    public BaseResponse<PostsVO> getPostVOById(@RequestBody PostQueryRequest postQueryRequest, HttpServletRequest request) {
        if (postQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        if (postQueryRequest.getPostId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        JsbPosts post = postService.getById(postQueryRequest.getPostId());
        if (post == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(postService.getPostVO(postQueryRequest.getLoginUserId(), post, request));
    }

    /**
     * 分页获取帖子列表
     *
     * @param postQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    @ApiOperation("所有帖子列表")
    public BaseResponse<Page<PostsVO>> listPostVOByPage(@RequestBody PostQueryRequest postQueryRequest,
                                                        HttpServletRequest request) {
        long current = postQueryRequest.getPageNum();
        long size = postQueryRequest.getPageSize();
        String loginUserId = postQueryRequest.getLoginUserId();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<JsbPosts> postPage = postService.page(new Page<>(current, size),
                postService.getQueryWrapper(postQueryRequest));
        return ResultUtils.success(postService.getPostVOPage(loginUserId, postPage, request));
    }

    /**
     * 分页获取当前用户创建的资源列表
     *
     * @param postQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    @ApiOperation("查询用户下的帖子列表")
    public BaseResponse<Page<PostsVO>> listMyPostVOByPage(@RequestBody PostQueryRequest postQueryRequest,
                                                          HttpServletRequest request) {
        if (postQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        if (StringUtils.isAnyBlank(postQueryRequest.getUserId())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户id为空");
        }
        long current = postQueryRequest.getPageNum();
        long size = postQueryRequest.getPageSize();
        String loginUserId = postQueryRequest.getLoginUserId();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<JsbPosts> postPage = postService.page(new Page<>(current, size),
                postService.getQueryWrapper(postQueryRequest));
        return ResultUtils.success(postService.getPostVOPage(loginUserId, postPage, request));
    }

    /**
     * 编辑（用户）
     *
     * @param postEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    @ApiOperation("编辑帖子")
    public BaseResponse<Boolean> editPost(@RequestBody PostEditRequest postEditRequest, HttpServletRequest request) {
        if (postEditRequest == null || postEditRequest.getPostId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        JsbPosts post = new JsbPosts();
        BeanUtils.copyProperties(postEditRequest, post);
        List<String> tags = postEditRequest.getTags();
        if (tags != null) {
            post.setTags(GSON.toJson(tags));
        }
        // 参数校验
        postService.validPost(post, false);
        long id = postEditRequest.getPostId();
        String userId = postEditRequest.getUserId();
        // 判断是否存在
        JsbPosts oldPost = postService.getById(id);
        ThrowUtils.throwIf(oldPost == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人可编辑
        if (!oldPost.getUserId().equals(userId)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = postService.updateById(post);
        return ResultUtils.success(result);
    }

}
